# -*- coding:utf-8 -*-
from datetime import datetime
import sys,os

"""
功能：
	1.用户注册，提示用户输入用户名和密码，然后获取当前注册时间，最后将用户名、密码、注册时间写入到文件。
	2.用户登录，只有三次错误机会，一旦错误则冻结账户（下次启动也无法登录，提示：用户已经冻结）。
"""



def register():
    """
    用户注册
    
    """
    print('-----用户注册----')
    while True:
        user = input('请输入用户(N退出)：')
        if user.upper() == 'N':
            return
        pwd = input('请输入密码：')
        create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        with open('db.txt',mode='a',encoding='utf-8') as f:
            line = '%s|%s|%s\n' % (user,pwd,create_time)
            f.write(line)

    
def login():
    """
    用户登录
    """
    print('用户登录')
    count = 0
    while True:
        user = input('请输入用户名')
        pwd = input('请输入密码：')
        
        #判断用户是否被冻结
        if os.path.exists('frozen.txt'):
            with open('frozen.txt','r',encoding='utf-8') as f:
                user_list = f.readlines()
            frozen_user_list = [item.strip() for item in user_list if item.strip()]
            if user in frozen_user_list:
                print('该用户已被冻结')
                continue   #return也可以
        
        # 用户未被冻结,检查用户名密码是否正确
        flag = False
        username_exist = False
        with open('db.txt',mode='r',encoding='utf-8') as f:
            for line in f:
                username,password,ctime = line.split('|')
                
                if username == user:
                    username_exist = True
                
                if username == user and password == pwd:
                    flag = True
                    print('登录成功')
                    sys.exit(0)
                    
        if not username_exist:
            print('用户名不存在')
            continue
        
        if not flag:
            print('用户名或密码错误')
            if count == 2:
                print('错误次数3次，冻结账号')
                with open('frozen.txt','a',encoing='utf-8') as f:
                    f.write(user+'\n')
                    return
            count += 1        
                
        
def run():
    """
    主函数  程序入口
    """
    func_dict = {'1':register,'2':login}
    while True:
        print('1.注册；2.登录')
        choice = input('请选择：')
        func_name = func_dict.get(choice)
        if not func_name:
            print('选择错误，重新选择')
            continue
        func_name()

if __name__ == '__main__':
    run()